package org.springframework.samples.petclinic.lift

import java.util.Locale
import scala.xml.NodeSeq

import net.liftweb.http.{LiftRules, S, SHtml}
import net.liftweb.util.Full

import org.springframework.context.MessageSource
import org.springframework.validation.{MapBindingResult,BindingResult,FieldError,ObjectError}

/**
 * Some utils for integrating Lift and Spring.
 */
object LiftUtils {

  def servletContext = LiftRules.context
  
  def clinic = Utils.getClinic(servletContext)
  
  def messageSource = Utils.getMessageSource(servletContext)
  
  private def springResultToLift(messageSource:MessageSource, result:BindingResult) = {
    for (elem <- new ForeachIterator(result.getFieldErrors.iterator)) {
      val fieldError = elem.asInstanceOf[FieldError]
      val msg = messageSource.getMessage(fieldError, Locale.ENGLISH)
      S.error(fieldError.getField, msg)
    }
    for (elem <- new ForeachIterator(result.getGlobalErrors.iterator)) {
      val objectError = elem.asInstanceOf[ObjectError]
      val msg = messageSource.getMessage(objectError, Locale.ENGLISH)
      S.error(msg)
    }
  }
  
  def toLiftErrors(result:BindingResult) = {
    springResultToLift(messageSource, result)
  }
  
  def field(label:String, fieldValue:String, func:String=>Any, attrs:(String,String)* ) = {
    val id:String = attrs.filter(_._1 == "id").map(_._2)(0)
    val errorTxt: List[NodeSeq] = S.messagesById(id)(S.errors)
    val error = errorTxt match {
      case List() => ""
      case _ => <span id = {id + ".errors"} class="errors">{errorTxt}</span>
    }
    val nullSafeValue: String = if (fieldValue == null) "" else fieldValue
    val inputText = SHtml.text(nullSafeValue, func, attrs :_* )
    <tr><th> {label} {error} <br/> {inputText} </th></tr>
  }



}
